using System;
using System.Collections.Generic;
using Comteck.Mappings;
using Comteck.Winforms.Extensions;
using ExpressMapper;
using ExpressMapper.Configuration;
using ExpressMapper.Extensions;

namespace Comteck.Winforms.AutoMapper {
  /// <summary>
  /// 
  /// </summary>
  public partial class AutoMapperContainer : BaseLog{

    private static AutoMapperContainer _Instance = null;

    public static AutoMapperContainer Instance {
      get {
        if (_Instance == null) {
          _Instance = new AutoMapperContainer();
        }

        return _Instance;
      }
    }

    /// <summary>
    /// 添加引用的规则
    /// </summary>
    public List<Action<IMapperConfigurationExpression>> Configurators { get; }

    /// <summary>
    /// 构造函数
    /// </summary>
    private AutoMapperContainer() {
      this.Configurators = new List<Action<IMapperConfigurationExpression>>();
    }

    /// <summary>
    /// 
    /// </summary>
    public void Initialize() {
      // 本程序集
      var thisAssembly = this.GetType().GetAssembly();

      // empty程序集
      this.Configurators.Add(
        cfg => cfg.AddProfiles(thisAssembly, typeof(EmptyProfile).GetAssembly())
      );

      // 映射配置
      void configurer(IMapperConfigurationExpression configuration) {
        // 根据配置文件映射
        foreach (var configurator in this.Configurators) {
          try {
            configurator(configuration);
          } catch (Exception ex) {
            Logger.Error(ex.Message, ex);
          }
        }
      }

      Mapper.Instance.Initialize(configurer);
    }

  }
}
